package chuangyi.com.org.ViewModel;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.databinding.Bindable;
import android.databinding.DataBindingUtil;
import android.databinding.ObservableDouble;
import android.databinding.adapters.CalendarViewBindingAdapter;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.CalendarView;
import android.widget.DatePicker;
import android.widget.NumberPicker;
import android.widget.Toast;

import com.android.databinding.library.baseAdapters.BR;
import com.solidfire.gson.internal.LinkedTreeMap;

import java.security.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import chuangyi.com.org.DOMIHome.Fragments.CommonFragment;
import chuangyi.com.org.DOMIHome.HomeActivity;
import chuangyi.com.org.DOMIHome.LoadingDialog;
import chuangyi.com.org.DOMIHome.ParagraphEditor;
import chuangyi.com.org.DOMIHome.PopupActivity;
import chuangyi.com.org.DOMIHome.R;
import chuangyi.com.org.DOMIHome.SaveContent;
import chuangyi.com.org.DOMIHome.Utils.HttpUtil;
import chuangyi.com.org.DOMIHome.Utils.Utils;
import chuangyi.com.org.DOMIHome.Utils.WebApi;
import chuangyi.com.org.DOMIHome.WaitActivityResult;
import chuangyi.com.org.DOMIHome.WxPayInfoModel;
import chuangyi.com.org.DOMIHome.adapter.ListBindingAdapter;
import chuangyi.com.org.DOMIHome.databinding.FSendXuanshangBinding;

/**
 * Created by zxh on 16/12/7.
 */

public class EditReward extends ArticleEditorBase implements SaveContent {
    private ListBindingAdapter amountList;
    private Date startDate;
    private Date endDate;
    private String amount;

    @Override
    protected boolean isArticle() {
        return false;
    }

    @Bindable
    public ListBindingAdapter getAmountList() {
        return amountList;
    }

    @Bindable
    public Date getStartDate() {
        return startDate;
    }

    public void setStartDate(Date startDate) {
        this.startDate = startDate;
        notifyPropertyChanged(BR.startDate);
    }

    @Bindable
    public Date getEndDate() {
        return endDate;
    }

    public void setEndDate(Date endDate) {
        this.endDate = endDate;
        notifyPropertyChanged(BR.endDate);
    }

    @Bindable
    public String getAmount() {
        return amount;
    }

    public void setAmount(String amount) {
        try {
            if ("".equals(amount) || amount == null) {
                amount = "0";
            }
            Double.parseDouble(amount);
            this.amount = amount;
        } catch (Exception ex) {

        }
        notifyPropertyChanged(BR.amount);
    }

    public EditReward(Context context) {
        super(context);
        super.getHandler().setTitle("发布悬赏");
        List<Integer> typeList = new ArrayList<Integer>();
        typeList.add(R.layout.i_amount);
        typeList.add(R.layout.i_transparent);
        amountList = new ListBindingAdapter(context, BR.amount, typeList);

        amount = "0.0";
        initAmountList();
    }

    /**
     * 点击发布按钮
     *
     * @param view
     */
    @Override
    public void onClickPublish(View view) {
        if (getId() == null || getParagraphs().getCount() == 0) {
            showToast("内容不能为空");
            return;
        }
        if (Utils.isNullOrEmpty(getTitle())) {
            showToast("内容不能为空");
            return;
        }
        if (Utils.isNullOrEmpty(getLabel())) {
            showToast("标签不能为空");
            return;
        }
        final Double value = Double.valueOf(amount);
        if (value > 0) {
            if (value < 1) {
                showToast("悬赏金额不能低于1元");
                return;
            }
            if (getStartDate() == null) {
                showToast("请输入开始时间");
                return;
            }
            if (getEndDate() == null) {
                showToast("请输入结束时间");
                return;
            }
        }
        LoadingDialog.getInstance(getContext()).show();
        new Thread(new Runnable() {
            @Override
            public void run() {
                if (value > 0) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            /**
                             * 启动支付
                             */
                            showPayActivity();
                        }
                    });
                } else {
                    if (sendReward(value, "") != null) {
                        showToast("您的问题已发布");
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                HomeActivity.cancelFragment();
                            }
                        });
                    }
                }
                LoadingDialog.getInstance(getContext()).dismiss();
            }
        }).start();
    }

    /**
     * 发布悬赏
     */
    private String sendReward(double money, String payType) {
        return WebApi.submitAsk(getContext(), getId(), getStartDate(), getEndDate(), money, payType);
    }

    /**
     * 选择开始日期
     *
     * @param view
     */
    public void onPickStartDate(View view) {
        showPickDateFragment(true);
    }

    /**
     * 选择开始日期
     *
     * @param view
     */
    public void onPickEndDate(View view) {
        showPickDateFragment(false);
    }

    public void showPickDateFragment(final boolean isStartDate) {
        final SelectDateModel dateSelector = new SelectDateModel(getContext());
        dateSelector.getHandler().setTitle("选择日期");
        CommonFragment fragment = new CommonFragment();
        fragment.setVariableId(BR.dateSelector);
        fragment.setLayoutId(R.layout.f_pick_date);
        fragment.setDataModel(dateSelector);
        fragment.setInitCallback(new CommonFragment.Callback() {
            @Override
            public void viewCreated(View root) {
                CalendarView datePicker = (CalendarView) root.findViewById(R.id.datePicker);
                datePicker.setOnDateChangeListener(new CalendarView.OnDateChangeListener() {
                    @Override
                    public void onSelectedDayChange(CalendarView calendarView, int i, int i1, int i2) {
                        Calendar calendar = Calendar.getInstance();
                        calendar.set(i, i1, i2);
                        dateSelector.setSelectedDate(calendar.getTime());
                    }
                });
                datePicker.setMinDate(Calendar.getInstance().getTimeInMillis());

                Calendar calendar = Calendar.getInstance();
                if (isStartDate && getStartDate() != null) {
                    calendar.setTime(getStartDate());
                } else if (!isStartDate && getEndDate() != null) {
                    calendar.setTime(getEndDate());
                }

                datePicker.setDate(calendar.getTimeInMillis());

                Calendar now = Calendar.getInstance();

                NumberPicker hourPicker = (NumberPicker) root.findViewById(R.id.hourSelector);
                String[] data = new String[24];
                for (int i = 0; i < 24; i++) {
                    data[i] = String.format(Locale.CHINESE, "%02d", i);
                }
                hourPicker.setDisplayedValues(data);
                hourPicker.setMinValue(0);
                hourPicker.setMaxValue(23);
                hourPicker.setValue(calendar.get(Calendar.HOUR_OF_DAY));


                dateSelector.setSelectedDate(calendar.getTime());
                dateSelector.setHour(String.format(Locale.CHINESE, "%02d", calendar.get(Calendar.HOUR_OF_DAY)));
                dateSelector.setMinute(String.format(Locale.CHINESE, "%02d", calendar.get(Calendar.MINUTE)));

                NumberPicker minutePicker = (NumberPicker) root.findViewById(R.id.minuteSelector);
                data = new String[60];
                for (int i = 0; i < 60; i++) {
                    data[i] = String.format(Locale.CHINESE, "%02d", i);
                }
                minutePicker.setDisplayedValues(data);
                minutePicker.setMinValue(0);
                minutePicker.setMaxValue(59);
                minutePicker.setValue(calendar.get(Calendar.MINUTE));

                hourPicker.setOnValueChangedListener(new NumberPicker.OnValueChangeListener() {
                    @Override
                    public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
                        String[] data = picker.getDisplayedValues();
                        dateSelector.setHour(data[newVal]);
                        Date date = dateSelector.getSelectedDate();
                        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
                        String time = String.format(Locale.CHINESE, "%s %s:%s", format.format(date),
                                dateSelector.getHour(), dateSelector.getMinute());
                        dateSelector.setSelectedDate(Utils.getDateFromFormat(time, "yyyy-MM-dd HH:mm"));
                    }
                });

                minutePicker.setOnValueChangedListener(new NumberPicker.OnValueChangeListener() {
                    @Override
                    public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
                        String[] data = picker.getDisplayedValues();
                        dateSelector.setMinute(data[newVal]);
                        Date date = dateSelector.getSelectedDate();
                        if (dateSelector.getHour() == null) {
                            dateSelector.setHour("00");
                        }
                        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
                        String time = String.format(Locale.CHINESE, "%s %s:%s", format.format(date),
                                dateSelector.getHour(), dateSelector.getMinute());
                        dateSelector.setSelectedDate(Utils.getDateFromFormat(time, "yyyy-MM-dd HH:mm"));
                    }
                });

                Button button = (Button) root.findViewById(R.id.ok);
                button.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        Date selected = dateSelector.getSelectedDate();
                        if (selected == null) {
                            selected = Calendar.getInstance().getTime();
                        }
                        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
                        String dateStr = format.format(selected);

                        selected = Utils.getDateFromFormat(String.format("%s %s:%s", dateStr,
                                dateSelector.getHour(), dateSelector.getMinute()),
                                "yyyy-MM-dd HH:mm");

                        Date now = Calendar.getInstance().getTime();
                        if (now.compareTo(selected) > 0) {
                            Toast.makeText(getContext(), "选择的日期无效", Toast.LENGTH_SHORT).show();
                            return;
                        }
                        if (isStartDate) {
                            if (getEndDate() == null || selected.compareTo(getEndDate()) > 0) {
                                setEndDate(selected);
                            }
                            setStartDate(selected);
                        } else {
                            if (getStartDate() == null || selected.compareTo(getStartDate()) < 0) {
                                setStartDate(selected);
                            }
                            setEndDate(selected);
                        }
                        HomeActivity.popFragment();
                    }
                });
            }
        });
        HomeActivity.switchFragment((Activity) getContext(), fragment);
    }

    /**
     * 显示付款界面
     */
    private void showPayActivity() {
        Activity activity = (Activity) getContext();
        final PayModel model = new PayModel(getContext(), Double.parseDouble(amount));
        model.setTitle("赏金支付");

//        model.setResultCallback(new PayModel.ResultCallback() {
//            @Override
//            public void onSuccess() {
//
//            }
//
//            @Override
//            public void onCancel() {
//                return;
//            }
//
//            @Override
//            public void onError() {
//                return;
//            }
//        });

        model.setPayCallback(new PayModel.Callback() {

            @Override
            public boolean onPay(final PayItem payType) {
                // 用户选择支付方式后回掉此方法
                // payType.getType()获取支付方式，PayModel.PAY_ALI表示支付宝付款、
                // PayModel.PAY_WX表示微信付款
                // 返回true关闭选择支付方式弹窗
                // 打开的新窗口的返回结果请在本类的onActivityResult中处理
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        String type = payType.getType() == PayModel.PAY_ALI ? "ali" : "wx";
                        Log.i("DOMIHome", type);
                        String result = sendReward(model.getAmount(), type);
                        if (result == null)
                            return;
                        if (payType.getType() == PayModel.PAY_ALI) {
                            LinkedTreeMap map = HttpUtil.fromJson(result, LinkedTreeMap.class);
                            result = (String) map.get("orderinfo");
                            payType.setPayData(result);
                        } else {
                            LinkedTreeMap map = HttpUtil.fromJson(result, LinkedTreeMap.class);
                            map = (LinkedTreeMap) map.get("orderinfo");
                            WxPayInfoModel wxModel = new WxPayInfoModel();
                            wxModel.setAppid((String) map.get("appid"));
                            wxModel.setNoncestr((String) map.get("noncestr"));
                            wxModel.setPackage((String) map.get("package"));
                            wxModel.setPartnerid((String) map.get("partnerid"));
                            wxModel.setPrepayid((String) map.get("prepayid"));
                            wxModel.setSign((String) map.get("sign"));
                            wxModel.setTimestamp((String) map.get("timestamp"));
                            payType.setPayData(wxModel);
                        }
                        payType.getParent().callPay(payType);
                    }
                }).start();
                return false;
            }
        });
        PopupActivity.startActivityForResult(activity, R.layout.v_dialog_advice_pay,
                HomeActivity.REQUEST_PAY, BR.payModel, model);
    }

    /**
     * 显示悬赏发布成功弹窗
     */
    private void showPublishSuccess() {
        Activity activity = (Activity) getContext();
        DialogModel model = new DialogModel(activity);
        PopupActivity.startActivityForResult(activity, R.layout.v_dialog_send_xs_success,
                HomeActivity.REQUEST_DIALOGTIP, BR.model, model);
    }

    private void initAmountList() {
        Context context = getContext();
        AmountItem item = new AmountItem(context, "￥10", 10, this);
        amountList.add(item);
        item = new AmountItem(context, "￥50", 50, this);
        amountList.add(item);
        item = new AmountItem(context, "￥100", 100, this);
        amountList.add(item);
        item = new AmountItem(context, "￥200", 200, this);
        amountList.add(item);
        item = new AmountItem(context, "￥500", 500, this);
        amountList.add(item);
        item = new AmountItem(context, "￥1000", 1000, this);
        amountList.add(item);
        item = new AmountItem(context, "只提问不悬赏", 0, this);
        item.setLayout(R.layout.i_transparent);
        amountList.add(item);
        item = new AmountItem(context, "只提问不悬赏", 0, this);
        amountList.add(item);
    }

    @Override
    public boolean check() {
        return true;
    }

    @Override
    public void save() {
        if (Utils.isNullOrEmpty(getTitle()) && Utils.isNullOrEmpty(getLabel())
                && Utils.isNullOrEmpty(getContent())) {
            HomeActivity.cancelFragment();
            return;
        }
        new AlertDialog.Builder(getContext()).setTitle("提示").setMessage("确定退出编辑吗？")
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        HomeActivity.cancelFragment();
                    }
                })
                .setNegativeButton("取消", null).show();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == HomeActivity.REQUEST_DIALOGTIP) {
            HomeActivity.cancelFragment();
            return;
        }
        if (resultCode == Activity.RESULT_OK) {
            if (requestCode == HomeActivity.REQUEST_PAY) {
                HomeActivity.cancelFragment();
                DialogModel model = new DialogModel(getContext());
                PopupActivity.startActivity((Activity) getContext(), R.layout.v_dialog_send_xs_success,
                        BR.model, model);
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }
}
